package com.hzhr.extdevice.controller;

import com.hzhr.extdevice.Global;
import com.hzhr.extdevice.aspect.Author;
import com.hzhr.extdevice.constant.ReturnCodeConst;
import com.hzhr.extdevice.mapper.device.*;
import com.hzhr.extdevice.model.database.device.*;
import com.hzhr.extdevice.model.response.BaseResponse;
import com.hzhr.extdevice.service.SMSService;
import com.hzhr.extdevice.util.StringHelper;
import com.hzhr.extdevice.util.TConverter;
import com.hzhr.iot.core.util.HzhrDateUtil;
import com.hzhr.iot.device.sdk.model.alarmData.AlarmDataPostModel;
import com.hzhr.iot.device.sdk.service.Device_AlarmDataService;
import com.hzhr.iot.report.sdk.template.ReportTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "迅腾数据接入接口", description = "迅腾数据接入接口")
@RestController
@RequestMapping(value = "/xunteng")
public class XuntengController {
    @Autowired
    private SMSService smsService;
    @Autowired
    DevCollectDeviceMapper devCollectDeviceMapper;
    @Autowired
    DevIotDeviceMapper devIotDeviceMapper;
    @Autowired
    DevCollectDataMapper devCollectDataMapper;
    @Autowired
    DevRegulatorCollectDataMapper devRegulatorCollectDataMapper;
    @Autowired
    DevAlarmDataMapper devAlarmDataMapper;
    @Autowired
    Device_AlarmDataService device_alarmDataService;
    @Autowired
    Global global;
    @Autowired
    HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(getClass());


    @ApiOperation(value = "新增采集设备")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", dataType = "int", paramType = "query", required = true, value = "设备类型,参考数据字典设备类型(SBLX)"),
            @ApiImplicitParam(name = "iotdeviceid", dataType = "String", paramType = "query", required = true, value = "所属远程设备编号(最大36个字符)"),
            @ApiImplicitParam(name = "deviceid", dataType = "String", paramType = "query", required = true, value = "采集设备编号(最大36个字符)"),
            @ApiImplicitParam(name = "gascompanyId", dataType = "String", paramType = "query", required = true, value = "所属燃气公司,参考数据字典燃气公司(RQGS)"),
            @ApiImplicitParam(name = "address", dataType = "String", paramType = "query", required = false, value = "安装地址,最大50个字符"),
            @ApiImplicitParam(name = "deptnames", dataType = "String", paramType = "query", required = false, value = "所属部门列表,多个部门之间请用逗号分隔"),
            @ApiImplicitParam(name = "installtime", value = "安装时间，形如2018-01-01 23:00:00", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "longitude", dataType = "double", paramType = "query", required = false, value = "经度，保留6位小数以百度地图为准116.339878(地球仪东西方向为经)"),
            @ApiImplicitParam(name = "latitude", dataType = "double", paramType = "query", required = false, value = "纬度，保留6位小数以百度地图为准39.954105(地球仪南北方向为纬)"),
    })
    @Author
    @RequestMapping(value = "/equipcollect/add", method = RequestMethod.POST)
    public Object add(@RequestParam(value = "type", required = true) int type,
            @RequestParam(value = "iotdeviceid", required = true) String iotdeviceid,
            @RequestParam(value = "deviceid", required = true) String deviceid,
            @RequestParam(value = "gascompanyId", required = true) String gascompanyId,
            @RequestParam(value = "address", required = false, defaultValue = "") String address,
            @RequestParam(value = "deptnames", required = false, defaultValue = "") String deptnames,
            @RequestParam(value = "installtime", required = false, defaultValue = "") String installtime,
            @RequestParam(value = "longitude", required = false, defaultValue = "0") double longitude,
            @RequestParam(value = "latitude", required = false, defaultValue = "0") double latitude) throws Exception {
        return new BaseResponse("0", "成功", "");
    }

    @ApiOperation(value = "编辑采集设备")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", dataType = "int", paramType = "query", required = true, value = "设备类型,参考数据字典设备类型(SBLX)"),
            @ApiImplicitParam(name = "iotdeviceid", dataType = "String", paramType = "query", required = true, value = "所属远程设备编号(最大36个字符)"),
            @ApiImplicitParam(name = "deviceid", dataType = "String", paramType = "query", required = true, value = "采集设备编号(最大36个字符)"),
            @ApiImplicitParam(name = "gascompanyId", dataType = "String", paramType = "query", required = true, value = "所属燃气公司,参考数据字典燃气公司(RQGS)"),
            @ApiImplicitParam(name = "address", dataType = "String", paramType = "query", required = false, value = "安装地址,最大50个字符"),
            @ApiImplicitParam(name = "deptnames", dataType = "String", paramType = "query", required = false, value = "所属部门列表,多个部门之间请用逗号分隔"),
            @ApiImplicitParam(name = "installtime", value = "安装时间，形如2018-01-01 23:00:00", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "longitude", dataType = "double", paramType = "query", required = false, value = "经度，保留6位小数以百度地图为准116.339878(地球仪东西方向为经)"),
            @ApiImplicitParam(name = "latitude", dataType = "double", paramType = "query", required = false, value = "纬度，保留6位小数以百度地图为准39.954105(地球仪南北方向为纬)")
    })
    @Author
    @RequestMapping(value = "/equipcollect/mod", method = RequestMethod.POST)
    public Object mod(@RequestParam(value = "type", required = true) int type,
                      @RequestParam(value = "deviceid", required = true) String deviceid,
                      @RequestParam(value = "iotdeviceid", required = true) String iotdeviceid,
                      @RequestParam(value = "gascompanyId", required = true) String gascompanyId,
                      @RequestParam(value = "address", required = false, defaultValue = "") String address,
                      @RequestParam(value = "deptnames", required = false, defaultValue = "") String deptnames,
                      @RequestParam(value = "installtime", required = false, defaultValue = "") String installtime,
                      @RequestParam(value = "longitude", required = false, defaultValue = "0") double longitude,
                      @RequestParam(value = "latitude", required = false, defaultValue = "0") double latitude) throws  Exception {
        return new BaseResponse(ReturnCodeConst.SUCCESS, "成功", "");
    }

    @ApiOperation(value = "删除采集设备")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iotdeviceid", dataType = "String", paramType = "query", required = true, value = "所属远程设备编号,硬件编码(最大允许36位)）"),
            @ApiImplicitParam(name = "deviceid", dataType = "String", paramType = "query", required = true, value = "采集设备编号,硬件编码(最大允许36位)"),})
    @Author
    @RequestMapping(value = "/equipcollect/del", method = RequestMethod.POST)
    public Object del(@RequestParam(value = "iotdeviceid", required = true) String iotdeviceid,
                      @RequestParam(value = "deviceid", required = true) String deviceid) throws Exception {
        return new BaseResponse(ReturnCodeConst.SUCCESS, "成功", "");
    }

    @ApiOperation(value = "上报采集设备运行状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iotdeviceid", dataType = "String", paramType = "query", required = true, value = "所属远程设备编号,最大36硬件编码"),
            @ApiImplicitParam(name = "deviceid", dataType = "String", paramType = "query", required = true, value = "采集设备编号,最大36硬件编码"),
            @ApiImplicitParam(name = "staflowrate", dataType = "double", paramType = "query", required = false, value = "标况瞬时流量,double(21,4))"),
            @ApiImplicitParam(name = "statotalflow", dataType = "double", paramType = "query", required = false, value = "标况累计流量,double(21,4))"),
            @ApiImplicitParam(name = "temperature", dataType = "double", paramType = "query", required = false, value = "温度,double(21,4))"),
            @ApiImplicitParam(name = "pressure", dataType = "double", paramType = "query", required = false, value = "压力,double(21,4))"),
            @ApiImplicitParam(name = "concentration", dataType = "double", paramType = "query", required = false, value = "浓度,double(21,4))"),
            @ApiImplicitParam(name = "inputpressure", dataType = "double", paramType = "query", required = false, value = "进口压力,double(21,4))"),
            @ApiImplicitParam(name = "power", dataType = "double", paramType = "query", required = false, value = "电池电量,double(21,4))"),
            @ApiImplicitParam(name = "reporttime", value = "采集时间,(yyyy-MM-dd HH:mm:ss)", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "alarmstatus", allowMultiple = true, dataType = "Integer", paramType = "query", required = false, value = "报警状态,701 正常 702 温度异常 703 压力异常 704 低电 705 浓度报警")
    })
    @Author
    @PostMapping("/equipcollect/report")
    public Object report(@RequestParam(value = "iotdeviceid", required = true) String iotdeviceid,
                         @RequestParam(value = "deviceid", required = true) String deviceid,
                         @RequestParam(value = "staflowrate", required = false, defaultValue = "0") Double[] staflowrate,
                         @RequestParam(value = "statotalflow", required = false, defaultValue = "0") Double[] statotalflow,
                         @RequestParam(value = "temperature", required = false, defaultValue = "0") Double[] temperature,
                         @RequestParam(value = "pressure", required = false, defaultValue = "0") Double[] pressure,
                         @RequestParam(value = "concentration", required = false, defaultValue = "0") Double[] concentration,
                         @RequestParam(value = "inputpressure", required = false, defaultValue = "0") Double[] inputpressure,
                         @RequestParam(value = "power", required = false, defaultValue = "0") Double[] power,
                         @RequestParam(value = "reporttime", required = false) String reporttime,
                         @RequestParam(value = "alarmstatus", required = false, defaultValue = "0") Integer[] alarmstatus) throws Exception {
        String token = request.getParameter("token");
        if (!"274e0c50-dd91-4874-92b9-8bede5bbf377".equals(token)) return new BaseResponse(ReturnCodeConst.NO_LOGIN, "请登录后重试");


        logger.info("正在接受数据 设备号：" + deviceid);

        //如果没有物联网设备则新增
        String iotCategoryCode = "4";
        DevIotDeviceExample example = new DevIotDeviceExample();
        example.createCriteria().andCodeEqualTo(deviceid).andCategoryCodeEqualTo(iotCategoryCode);
        List<DevIotDevice> iotDevices = this.devIotDeviceMapper.selectByExample(example);
        DevIotDevice iotDevice = iotDevices.size() > 0 ? iotDevices.get(0) : null;
        if (iotDevice == null) {
            iotDevice = new DevIotDevice();
            iotDevice.setCode(deviceid);
            iotDevice.setCategoryCode(iotCategoryCode);
            iotDevice.setCompanyId(Integer.valueOf(8));
            iotDevice.setGasCompanyId(Integer.valueOf(9));
            iotDevice.setDeptId(Integer.valueOf(2));
            iotDevice.setIotPlatformCode("4");
            iotDevice.setIotPlatformDeviceId(deviceid);
            iotDevice.setCreateTime(new Date());
            iotDevice.setCreateUserId(Integer.valueOf(0));
            iotDevice.setResourceCode("01000801");
            iotDevice.setIsValid("1");
            iotDevice.setState("1");
            this.devIotDeviceMapper.insert(iotDevice);
        }

        //新增采集数据
        if (!StringUtils.isEmpty(reporttime)) {
            DevCollectDevice collectDevice = null;
            Integer collectDeviceId = iotDevice.getCollectDeviceId();
            if (collectDeviceId != null) {
                DevCollectDeviceExample example1 = new DevCollectDeviceExample();
                example1.createCriteria().andIdEqualTo(collectDeviceId).andIsValidEqualTo("1");
                List<DevCollectDevice> collectDevices = this.devCollectDeviceMapper.selectByExample(example1);
                collectDevice = (collectDevices.size() > 0) ? (DevCollectDevice)collectDevices.get(0) : null;
            }

            Date currentTm = HzhrDateUtil.strToDate(reporttime, "yyyyMMddHHmmss");

            DevRegulatorCollectDataExample example2 = new DevRegulatorCollectDataExample();
            example2.createCriteria().andIotDeviceIdEqualTo(iotDevice.getId()).andCollectTimeEqualTo(currentTm).andIsValidEqualTo("1");
            int count = devRegulatorCollectDataMapper.countByExample(example2);
            if (count == 0) {
                DevRegulatorCollectData devRegulatorCollectData = new DevRegulatorCollectData();
                if (collectDevice != null) {
                    devRegulatorCollectData.setCollectDeviceId(collectDevice.getId());
                }
                devRegulatorCollectData.setIotDeviceId(iotDevice.getId());
                if (inputpressure != null && inputpressure.length > 0) {
                    devRegulatorCollectData.setInPressure(inputpressure[0]);
                }
                if (pressure != null && pressure.length > 0) {
                    devRegulatorCollectData.setOutPressure1(pressure[0]);
                    devRegulatorCollectData.setOutPressure2(pressure.length > 1 ? pressure[1] : null);
                    devRegulatorCollectData.setOutPressure3(pressure.length > 2 ? pressure[2] : null);
                    devRegulatorCollectData.setOutPressure4(pressure.length > 3 ? pressure[3] : null);
                }
                if (staflowrate != null && staflowrate.length > 0) {
                    devRegulatorCollectData.setOutStaFlowRate1(staflowrate[0]);
                    devRegulatorCollectData.setOutStaFlowRate2(staflowrate.length > 1 ? staflowrate[1] : null);
                    devRegulatorCollectData.setOutStaFlowRate3(staflowrate.length > 2 ? staflowrate[2] : null);
                    devRegulatorCollectData.setOutStaFlowRate4(staflowrate.length > 3 ? staflowrate[3] : null);
                }
                if (statotalflow != null && statotalflow.length > 0) {
                    devRegulatorCollectData.setOutStaTotalFlow1(statotalflow[0]);
                    devRegulatorCollectData.setOutStaTotalFlow2(statotalflow.length > 1 ? statotalflow[1] : null);
                    devRegulatorCollectData.setOutStaTotalFlow3(statotalflow.length > 2 ? statotalflow[2] : null);
                    devRegulatorCollectData.setOutStaTotalFlow4(statotalflow.length > 3 ? statotalflow[3] : null);
                }
                if (temperature != null && temperature.length > 0) {
                    devRegulatorCollectData.setOutTemperature1(new BigDecimal(temperature[0]).floatValue());
                    devRegulatorCollectData.setOutTemperature2(temperature.length > 1 ? new BigDecimal(temperature[1]).floatValue() : null);
                    devRegulatorCollectData.setOutTemperature3(temperature.length > 2 ? new BigDecimal(temperature[2]).floatValue() : null);
                    devRegulatorCollectData.setOutTemperature4(temperature.length > 3 ? new BigDecimal(temperature[3]).floatValue() : null);
                }
                devRegulatorCollectData.setCollectTime(currentTm);
                devRegulatorCollectData.setCreateTime(new Date());
                devRegulatorCollectData.setState("1");
                devRegulatorCollectData.setIsValid("1");
                devRegulatorCollectDataMapper.insert(devRegulatorCollectData);


                if (alarmstatus != null && alarmstatus.length > 0) {
                    for (Integer item :
                            alarmstatus) {
                        if (item != 701) {
                            Map<String, String> header = new HashMap<>();
                            header.put("token", global.getFirstToken());
                            Map<String, Object> query = new HashMap<>();
                            AlarmDataPostModel alarmDataPostModel = new AlarmDataPostModel();
                            if (collectDevice != null) {
                                alarmDataPostModel.setCollectDeviceId(collectDevice.getId());
                                alarmDataPostModel.setGasUserId(collectDevice.getGasUserId());
                            }
                            alarmDataPostModel.setIotDeviceId(iotDevice.getId());
                            alarmDataPostModel.setCurrentTm(currentTm.getTime());
                            if (item == 702) {
                                alarmDataPostModel.setAlarmType("1011");
                            } else if (item == 703) {
                                alarmDataPostModel.setAlarmType("1012");
                            } else if (item == 704) {
                                alarmDataPostModel.setAlarmType("1013");
                            }
                            device_alarmDataService.post(header, query, alarmDataPostModel);
                        }
                    }
                }
            }
        }


        return new BaseResponse(ReturnCodeConst.SUCCESS, "成功", "");
    }

    @ApiOperation(value = "新增远传设备")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceid", dataType = "String", paramType = "query", required = true, value = "设备编号(最大36和字符)"),
            @ApiImplicitParam(name = "type", dataType = "int", paramType = "query", required = true, value = "设备类型,参考数据字典设备类型(SBLX)"),
            @ApiImplicitParam(name = "address", dataType = "String", paramType = "query", required = false, value = "安装地址,最大50个字符"),
            @ApiImplicitParam(name = "longitude", dataType = "double", paramType = "query", required = false, value = "经度，保留6位小数以百度地图为准116.339878(地球仪东西方向为经)"),
            @ApiImplicitParam(name = "latitude", dataType = "double", paramType = "query", required = false, value = "纬度，保留6位小数以百度地图为准39.954105(地球仪南北方向为纬)"),
            @ApiImplicitParam(name = "imgUrls", dataType = "String[]", paramType = "query", required = false, value = "照片路径列表，多个请使用逗号分隔")
    })
    @Author
    @RequestMapping(value = "/equipiot/add", method = RequestMethod.POST)
    public Object addIot(@RequestParam(value = "deviceid", required = true) String deviceid,
                      @RequestParam(value = "type", required = true) int type,
                      @RequestParam(value = "address", required = false, defaultValue = "") String address,
                      @RequestParam(value = "longitude", required = false, defaultValue = "0") double longitude,
                      @RequestParam(value = "latitude", required = false, defaultValue = "0") double latitude,
                      @RequestParam(value = "imgUrls", required = false) String[] imgUrls) throws Exception {

        return new BaseResponse(ReturnCodeConst.SUCCESS, "成功", "");
    }


    @ApiOperation(value = "修改远传设备")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceid", dataType = "String", paramType = "query", required = true, value = "设备编号(最大36个字符)"),
            @ApiImplicitParam(name = "type", dataType = "int", paramType = "query", required = true, value = "设备类型,参考数据字典设备类型(SBLX)"),
            @ApiImplicitParam(name = "address", dataType = "String", paramType = "query", required = false, value = "安装地址,最大50个字符"),
            @ApiImplicitParam(name = "longitude", dataType = "double", paramType = "query", required = false, value = "经度，保留6位小数以百度地图为准116.339878(地球仪东西方向为经)"),
            @ApiImplicitParam(name = "latitude", dataType = "double", paramType = "query", required = false, value = "纬度，保留6位小数以百度地图为准39.954105(地球仪南北方向为纬)"),
            @ApiImplicitParam(name = "imgUrls", dataType = "String[]", paramType = "query", required = false, value = "照片路径列表，多个请使用逗号分隔")
    })
    @Author
    @RequestMapping(value = "/equipiot/mod", method = RequestMethod.POST)
    public Object modIot(@RequestParam(value = "deviceid", required = true) String deviceid,
                      @RequestParam(value = "type", required = true) int type,
                      @RequestParam(value = "address", required = false, defaultValue = "") String address,
                      @RequestParam(value = "longitude", required = false, defaultValue = "0") Double longitude,
                      @RequestParam(value = "latitude", required = false, defaultValue = "0") Double latitude,
                      @RequestParam(value = "imgUrls", required = false) String[] imgUrls) throws Exception {

        return new BaseResponse(ReturnCodeConst.SUCCESS, "成功", "");
    }


    @ApiOperation(value = "删除远传设备")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceid", dataType = "String", paramType = "query", required = true, value = "设备编号(最大36个字符)")})
    @Author
    @RequestMapping(value = "/equipiot/del", method = RequestMethod.POST)
    public Object delIot(@RequestParam(value = "deviceid", required = true) String deviceid) throws Exception {
        return new BaseResponse(ReturnCodeConst.SUCCESS, "成功", "");
    }

}
